package com.three.sso.admin.service;


import com.three.core.entity.Menu;
import com.three.core.entity.User;
import com.three.sso.admin.feign.UserFeign;
import com.three.core.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

//sso不负责操作数据库 所有对数据库的操作交于services
@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserFeign userFeign;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //根据账号查询用户信息
        R<User> r = userFeign.getByName(userName);
        if(r.getData()==null){
            throw new UsernameNotFoundException("用户未找到");
        }
        //获取用户信息
        User u = r.getData();
        //根据用户信息查询用户具有的权限
        R<List<Menu>> permissionByUserId = userFeign.getPermissionByUserId(u.getUserId());
        List<Menu> data = permissionByUserId.getData();
        List<SimpleGrantedAuthority> authorities = data.stream()
                .map(Menu::getPerms)  // 先提取权限字符串
                .filter(perms -> perms != null && !perms.trim().isEmpty()) // 过滤空值
                .map(SimpleGrantedAuthority::new)  // 转换为权限对象
                .collect(Collectors.toList());


        org.springframework.security.core.userdetails.User user=new org.springframework.security.core.userdetails.User
                (u.getUserName(),u.getPassword(),authorities);
        return user;
    }
}
